

public class BetweenReverse {
    class ListNode{
        public int val;
        public ListNode next;
        public ListNode(int val){
            this.val = val;
        }
    }
    public static ListNode head;
    public ListNode create(){
        ListNode a1 = new ListNode(1);
        ListNode a2 = new ListNode(2);
        ListNode a3 = new ListNode(3);
        ListNode a4 = new ListNode(4);
        ListNode a5 = new ListNode(5);
        a1.next = a2;
        a2.next = a3;
        a3.next = a4;
        a4.next = a5;
        head = a1;
        return head;
    }

    public ListNode reverseBetween (ListNode head, int m, int n) {
        ListNode unreal = new ListNode(1);
        unreal.next = head;
        ListNode pre = unreal;
        for(int i = 1;i < m ; i ++){
            pre = pre.next;
        }
        ListNode cur = pre.next;
        for(int i = m; i < n; i ++){
            ListNode next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return head;
    }

    public static void main(String[] args) {
        BetweenReverse betweenReverse = new BetweenReverse();
        betweenReverse.create();
        betweenReverse.reverseBetween(head,2,4);
        while (head != null){
            System.out.println(head.val);
            head = head.next;
        }

    }
}
